package it.low.game.core.action;

import it.low.game.core.element.ActiveElement;
import it.low.game.core.element.activity.Targetable;
import it.low.game.core.location.MapPoint;

public class Move extends Action{
		
	protected MapPoint startMapPosition = null;
	protected MapPoint endMapPosition = null;
	protected double cosAlpha = 0;
	protected double sinAlpha = 0;

	public Move(Targetable endMapPosition){
		super(Action.TYPE.MOVE, endMapPosition);
		this.endMapPosition = endMapPosition.getMapPosition();
	}
	
	public boolean start(ActiveElement activeElement){
		this.startMapPosition = activeElement.getMapPosition();
		this.setPath(activeElement.getMapPosition(), endMapPosition.getMapPosition());
		return true;
	}
	
	public boolean resume(ActiveElement activeElement){
		this.startMapPosition = activeElement.getMapPosition();
		this.setPath(activeElement.getMapPosition(), endMapPosition.getMapPosition());
		return true;
	}
	
	public boolean run(ActiveElement executor, long elapsedTime){
		boolean isFinish = false;
		double delta = executor.getProperty(ActiveElement.MOV_SPEED)*elapsedTime;
		if(endMapPosition!=null){			
			if(executor.getMapPosition().isNear(endMapPosition,delta)){
				executor.setMapPosition(endMapPosition);
				isFinish = this.stop();
			}else{										
				double deltaX = delta*sinAlpha;
				double deltaY = delta*cosAlpha;							
				double newLocationX = executor.getMapPosition().getX() + deltaX;
				double newLocationY = executor.getMapPosition().getY() + deltaY;
				executor.setMapPosition(new MapPoint(newLocationX,newLocationY));				
			}			
		}
		return isFinish;
	}
	
	public boolean stop(){
		this.endMapPosition = null;		
		return true;
	}
	
	protected void setPath(MapPoint startPoint, MapPoint endPoint){
		this.endMapPosition = endPoint;
		
		double deltaTotX = endMapPosition.getX() - startPoint.getX();
		double deltaTotY = endMapPosition.getY() - startPoint.getY();
		
		cosAlpha = deltaTotY / (Math.sqrt(Math.pow(deltaTotX, 2) + Math.pow(deltaTotY, 2)));
		sinAlpha = deltaTotX / (Math.sqrt(Math.pow(deltaTotX, 2) + Math.pow(deltaTotY, 2)));
	}
	
}
